<template>
  <!-- 批量表格 --> 
  <div>
    <a-spin tip="Loading..." :spinning="id_Loading">
      <div v-for="item,index in datas" :key="index">
        <div class="batch-block check-table">
          <div class="table-btn selectBtn">
            <span>{{ item.account_id + '('+ item.name + ')' }}</span>
            <div>
              <a-input-number size="small" id="inputNumber" v-model="item.tabPlusNumber" :min="1" :max="50" />
              <a-button size="small" @click="addTableList(item,index)">添加计划</a-button>
            </div>
            <span style="padding:5px;">
              <a-icon style="cursor: pointer;" type="info-circle" title="复制第一条计划" />
            </span>
          </div>
          <batch-table 
            :conf.sync="item.tableConf"
            @checkChange="v=> checkChange(v,index,item)"
            :mapData="mapData"
            @deleteTableList="v=>deleteTableList(v,index)"
          ></batch-table>
        </div>
      </div>
      <!-- 提交规则 -->
      <div class="batch-block">
        <div class="batch-form-model">
          <div class="formModel-title">提交规则：</div>
          <a-form-model
            ref="ruleForms"
            :model="batchForm"
            :rules="rules"
            label_align='right'
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 18 }"
          >
            <a-form-model-item label="提交时间:" prop="rule">
              <a-radio-group
                v-model="batchForm.rule"
                button-style="solid"
              >
                <a-radio-button 
                  v-for="(item,index) in this.$global.battchType"
                  :key="index"
                  :value="item.value"
                > 
                  {{ item.label }}
                </a-radio-button>
              </a-radio-group>
            </a-form-model-item>
            <div v-if="batchForm.rule === 'now'">
              <span style="color:#BBBBBB;margin-left:10%;">提示: 点击保存后，全部广告计划和创意立即提交创建</span>
            </div>
            <!-- 定时  -->
            <a-form-model-item v-if="batchForm.rule === 'timming'" prop="rule_option.start_at">
              <span style="color:#BBBBBB;margin-left:10%;">提示: 点击保存后，全部广告计划和创意按下方设置时间提交创建</span>
              <div class="chunk-flex">
                <a-date-picker
                  v-model="batchForm.rule_option.start_at"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  show-time
                  type="date"
                />
              </div>
            </a-form-model-item>
            <!-- 分批 -->
            <a-form-model-item v-if="batchForm.rule === 'chunk' " required>
              <span style="color:#BBBBBB;margin-left:10%;">提示: 点击保存后，全部广告计划和创意按下方规则分批次提交创建，第一批保存后立即创建</span>
              <div class="chunk-flex">
                每隔
                <a-form-model-item prop="rule_option.chunk_minute">
                  <a-select v-model="batchForm.rule_option.chunk_minute" style="width:150px;">
                    <a-select-option
                      v-for="(item,index) in this.$global.batchSubmitTime"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
                  分钟，提交 
                <a-form-model-item prop="rule_option.chunk_size">
                  <a-input-number
                    v-model="batchForm.rule_option.chunk_size"
                    :min="1"
                    :max="100"
                  />
                  个计划
                </a-form-model-item>
              </div>

            </a-form-model-item>

            <a-form-model-item v-if="batchForm.rule === 'cycle' ">
              <span style="color:#BBBBBB;margin-left:10%;">提示: 点击保存后，全部广告计划和创意按下方规则重复多次创建（为避免广告计划名称重复，我们将为您自动增加时间后缀）</span>
              <div class="chunk-flex">
                每隔
                <a-form-model-item prop="rule_option.cycle_minute">
                  <a-select v-model="batchForm.rule_option.cycle_minute" style="width:150px;">
                    <a-select-option
                      v-for="(item,index) in this.$global.batchSubmitTime"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
                分钟提交一次全部计划，共提交 
                <a-form-model-item prop="rule_option.cycle_times">
                  <a-input-number
                    v-model="batchForm.rule_option.cycle_times"
                    :min="1"
                    :max="100"
                  />
                </a-form-model-item>
                次
              </div>
              <span style="color:red;margin-left:10%;">如广告创意不符合审核要求，重复提交可能会影响您的广告投放账号</span>
            </a-form-model-item>

          </a-form-model>

        </div>
      </div>

      <div class="next">
        <a-button type="primary" @click="save">
          保存
        </a-button>
      </div>
    </a-spin>
    <!-- 选择 -->
    <batch-select
      v-if="is_select"
      @batchChange="batchChange"
      :selectType="selectType"
      :selectAccountID="selectAccountID"
    ></batch-select>

  </div>
</template>

<script>
import { batchCreate } from "@/api/adv/batch"
import { getConvertListGet } from "@/api/adv/convert";  // 转化配置

export default {
  components:{ 
    'batchTable':()=> import('../components/batch/batchTable'),
    'batchSelect':() => import('../components/batch/batchSelect') 
  },
   data() {
    return {
      id_Loading:true,
      // table映射值
      mapData:{  
        campaign:JSON.parse(localStorage.getItem('campaign')).campaign_id, // 广告组
        package:JSON.parse(localStorage.getItem('ad')).package,  // 定向包
        CreativeGroups:JSON.parse(localStorage.getItem('CreativeGroups')), // 创意组
        convert:'',  // 转化配置
        // externalURL:''
      },
      tabPlusNumber:1,  // 添加计划条数
      // 创建规则
      batchForm:{
        rule:'now',
        rule_option:{}
      },
      rules:{
        rule: [{ required: true,message:'请选择批量方式', trigger: 'change' }],
        'rule_option.start_at': [{ required: true,message:'请选择定时创建时间', trigger: 'change' }],
        'rule_option.chunk_minute': [{ required: true,message:'请选择分批时间', trigger: 'change' }],
        'rule_option.chunk_size': [{ required: true,message:'请选择分批个数', trigger: 'change' }],
        'rule_option.cycle_minute': [{ required: true,message:'请选择重复周期', trigger: 'change' }],
        'rule_option.cycle_times': [{ required: true,message:'请选择重复次数', trigger: 'change' }],
      },

      // campaign:JSON.parse(localStorage.getItem('campaign')).campaign_id, //广告组
      datas:[],  // 总数据  tbody
      items:[],
      account_id:JSON.parse(localStorage.getItem('campaign')).account_id,

      selectAccountID:'',
      is_select:false,
      selectType:'',  // 当前选择的 key

      is_batch:'', // 是否批量
      checkAll:'',  // 是否全选
      selected:[],  // 已勾选
      clickOn:'',  // 单选当前索引(点击)
      tableIndex:'',  // 当前table索引
    };
  },
  created(){
    this.getLink()
    this.FormatData()
  },
  methods: {
    async getLink(){
      this.id_Loading = true
      const resConvert = await getConvertListGet( { status:'AD_CONVERT_STATUS_ACTIVE' } )  // 转化配置
      this.mapData.convert = resConvert.data
      this.id_Loading = false
    },
    FormatData(){
      // 拼接数据
      this.account_id.forEach( campaign => {
        let obj = {}
        obj.account_id = campaign.account_id
        obj.name = campaign.name
        obj.ad = JSON.parse( localStorage.getItem('ad') ) 
        obj.ad.advertiser_id = campaign.account_id
        obj.ad.productPlatform = ''

        obj.logoName = obj.ad.logoName
        delete obj.ad.logoName
        obj.creative = JSON.parse( localStorage.getItem('creative') )
        obj.creative.advertiser_id = campaign.account_id
        this.items.push(obj)
      });
      for (const item of this.items) {
        item.audience_templete_id = item.ad.package[0].id
        for (const campaign of this.mapData.campaign) {
          if( campaign.account_id === item.account_id ){
            item.ad.campaign_id = campaign.id
            break
          }
        }
      }
      let CreativeGroups = this.mapData.CreativeGroups
      for (const item of this.items) {
        let thead = [
          { key: 'key', name: '#',width:'80'},
          { key: 'name', name: '广告计划',tdType:'for',forkey:'ad',width:'120' },
          {
            thType:'checkboxAll', checkAll:false, tdType: 'checkbox', name: '推广标识',width:'120',
            key: 'logoName'
          },
          {
            thType:'checkboxAll', checkAll:false, tdType: 'checkbox', name: '所属广告组',width:'120',
            key: 'campaign_id',needID:'id',returnID:'name',forkey:'ad', mapData:'campaign'
          },
          {
            thType:'checkboxAll', checkAll:false, tdType: 'checkbox', name: '关联小说',width:'120',
            key: 'productPlatform',needID:'productPlatform',returnID:'name',forkey:'ad', mapData:'campaign'
          },
          { 
            thType:'checkboxAll', checkAll:false, tdType: 'checkbox',  name:'定向包',width:'120',
            key: 'audience_templete_id',needID:'id',returnID:'name',mapData:'package'
          },
          { 
            thType:'checkboxAll', checkAll:false, tdType: 'checkbox', name:'创意组',width:'120',
            key: 'creatives',forkey:'creative', returnID:'creative_group_name',mapData:'CreativeGroups'
          },
          {
            thType:'checkboxAll', checkAll:false, tdType: 'checkbox',width:'120',
            key: 'convert_id',forkey:'ad', name:'转化配置',mapData:'convert',returnID:'name',needID:'id'
          },
          { 
            thType:'checkboxAll', checkAll:false,tdType:'checkbox',returnID:'name',width:'120',
            key:'external_url',forkey:'ad', name: '落地页链接地址',title:true
          },
          { key: '@', name: '操作',tdType: 'operating',width:'50',}
        ]
        let obj = {
          account_id:item.account_id,
          name:item.name,
          tabPlusNumber:1,
          tableConf:{
            thead:thead,
            tbody:[]
          }
        }
        // 按创意组 深拷贝复制计划
        for (let i = 0; i < CreativeGroups.length; i++) {
          item.ad.name = item.ad.name.split('_')[0] + `_${this.$randomStr()}`  // 计划名称不能重复
          item.creative.creatives = JSON.parse( localStorage.getItem('CreativeGroups') )[i]
          obj.tableConf.tbody.push( this.$deepCopy(Object.assign( { 'key':i+1 },item )) )
        }
        this.datas.push(obj)
      }
    },
    // 批量、单项操作  x判断是否批量  操作
    checkChange(conf,index,item){
      if( conf.x === null ){
        this.is_batch = true
        if(conf.col.checkAll){  // 全选
          this.checkAll = true
        }else {
          this.checkAll = false
          let arr = []
          Object.keys(conf.checks).forEach((k) => {
            if ( k.replace(/-\d+/, '') === conf.col.key ){
               //已勾选
              if(conf.checks[k] === true){
                arr.push(k.split('-')[1])
              }
            }
          })
          this.selected = arr
        }
      }else {
        this.is_batch = false
        this.clickOn = conf.y
      }
      this.tableIndex = index
      // console.log(conf,index,item,'1')
      this.selectType = conf.col.key
      this.selectAccountID = this.datas[index].account_id // 账户id
      this.openOrCloseModel()
    },
    // 确认更改数据  type: 判断是否是对象、数组(double)   还是id。。(odd)
    batchChange(value,type){
      if(this.is_batch){  // 如果是批量操作
        if(this.checkAll){  // 如果是全选
          if(this.selectType === 'creatives'){   // 创意
            this.datas[this.tableIndex].tableConf.tbody.forEach( (ele,index) => {
              this.datas[this.tableIndex].tableConf.tbody[index].creative[this.selectType] = value[0]
            });
          }else if( this.selectType === 'audience_templete_id' || this.selectType === 'logoName' ){  // 定向包 、 标识
            this.datas[this.tableIndex].tableConf.tbody.forEach( (ele,index) => {
              this.datas[this.tableIndex].tableConf.tbody[index][this.selectType] = type === 'odd' ? value[0] : value[0].id
            });
          } else {  // 其他
            this.datas[this.tableIndex].tableConf.tbody.forEach( (ele,index) => {
              this.datas[this.tableIndex].tableConf.tbody[index].ad[this.selectType] = type === 'odd' ? value[0] : value[0].id
            });
          }
        }else {  // 批量勾选
          if( this.selectType === 'creatives' ){
            this.datas[this.tableIndex].tableConf.tbody.forEach( (ele,index) => {
              this.selected.forEach( idx => {
                if( index === parseInt(idx) ){
                  this.datas[this.tableIndex].tableConf.tbody[index].creative[this.selectType] = value[0]
                }
              });
            });
          }else if( this.selectType === 'audience_templete_id' || this.selectType === 'logoName' ){
            this.datas[this.tableIndex].tableConf.tbody.forEach( (ele,index) => {
              this.selected.forEach( idx => {
                if( index === parseInt(idx) ){
                  this.datas[this.tableIndex].tableConf.tbody[index][this.selectType] = type === 'odd' ? value[0] : value[0].id
                }
              });
            });
          } else {
            this.datas[this.tableIndex].tableConf.tbody.forEach( (ele,index) => {
              this.selected.forEach( idx => {
                if( index === parseInt(idx) ){
                  this.datas[this.tableIndex].tableConf.tbody[index].ad[this.selectType] = type === 'odd' ? value[0] : value[0].id
                }
              });
            });
          }
        }
      }else {
        if( this.selectType === 'creatives' ){
          this.datas[this.tableIndex].tableConf.tbody[this.clickOn].creative[this.selectType] = value[0]
        }else if( this.selectType === 'audience_templete_id' || this.selectType === 'logoName' ){
          this.datas[this.tableIndex].tableConf.tbody[this.clickOn][this.selectType] = type === 'odd' ? value[0] : value[0].id
        }else {
          this.datas[this.tableIndex].tableConf.tbody[this.clickOn].ad[this.selectType] = type === 'odd' ? value[0] : value[0].id
        }
      }
      this.openOrCloseModel()
    },
    openOrCloseModel(){
      this.is_select = !this.is_select
    },
    // 添加计划
    addTableList(item,index){
      let is_plus = item.tabPlusNumber + item.tableConf.tbody.length
      if( is_plus <= 50 ){
        for (let i = 0; i < item.tabPlusNumber; i++) {
          let _copy = this.$deepCopy( this.datas[index].tableConf.tbody[0] )
          _copy.ad.name = _copy.ad.name.split('_')[0] + `_${this.$randomStr()}`
          _copy.key = item.tableConf.tbody.length+1
          this.datas[index].tableConf.tbody.push(_copy)
        }
      }else {
        this.$Tip('计划条数不超过50条')
      }
    },
    // 删除计划
    deleteTableList(conf,index){
      this.datas[index].tableConf.tbody.splice(conf.index,1)
      // 删除之后，将key顺序排列
      if( conf.index !== this.datas[index].tableConf.tbody.length ){
        this.datas[index].tableConf.tbody.forEach( (items,index) => {
          items.key = (index+1)
        });
      }
    },
    // 保存
    async save(){
      this.$refs['ruleForms'].validate(valid => {
        if (valid) {
          this.id_Loading = true
          let subimt = {
            rule:this.batchForm.rule,
            rule_option:{},
            items:[],
          }
          if (this.batchForm.rule === 'timming') {
            subimt.rule_option.start_at = this.batchForm.rule_option.start_at
          }
          if (this.batchForm.rule === 'chunk') {
            subimt.rule_option.chunk_minute = this.batchForm.rule_option.chunk_minute
            subimt.rule_option.chunk_size = this.batchForm.rule_option.chunk_size
          }
          if (this.batchForm.rule === 'cycle') {
            subimt.rule_option.cycle_minute = this.batchForm.rule_option.cycle_minute
            subimt.rule_option.cycle_times = this.batchForm.rule_option.cycle_times
          }

          let datas = this.$deepCopy(this.datas)
          for (const items of datas) {
            for (const item of items.tableConf.tbody) {
             
              if( item.ad.hasOwnProperty('convert_id') && item.ad.convert_id === '' ) return alert(`${item.name}( ${item.account_id} ),第${item.key}条计划,请选择转化配置`) ,this.id_Loading =false
              if( item.ad.hasOwnProperty('external_url') && item.ad.external_url === '' ) return alert(`${item.name}( ${item.account_id} ),第${item.key}条计划,请选择落地页链接`),this.id_Loading =false
              if( item.hasOwnProperty('logoName') && item.logoName === '' ) return alert('请填写推广标识'), this.id_Loading =false

              // 创意组检测 
              if( item.creative.creatives.creativeMaterialMode === 'STATIC_ASSEMBLE' ){  //  程序化
                item.creative.creative_material_mode = 'STATIC_ASSEMBLE'

                let titles = []
                let image_lists = []
                for (const creative of item.creative.creatives.creativeList) {
                  let obj = {}
                  obj.image_mode = creative.materialItem.image_mode
                  if( creative.materialItem.material_type === 'image' ) {
                    obj.image_ids = [creative.materialItem.id]
                  }else if( creative.materialItem.material_type === 'video' ) {
                    obj.video_id = creative.materialItem.id  //视频id
                    obj.image_id = creative.coverImage.id    // 视频封面图片id(必需)
                  }
                  image_lists.push(obj)
                }
                for (const title of item.creative.creatives.titles) {
                  let obj = {}
                  obj.title = title
                  titles.push(obj)
                }
                item.creative.image_list = image_lists
                item.creative.title_list = titles
                item.creative.creatives = []
              }else {
                let noMode = []
                for (const creative of item.creative.creatives.creativeList) {
                  let obj = {}
                  obj.image_mode = creative.materialItem.image_mode
                  obj.title = creative.titleList[0]
                  if( creative.materialItem.material_type === "image" ) {
                    obj.image_ids = [creative.materialItem.id]
                  }else if( creative.materialItem.material_type === "video" ){
                    obj.video_id = creative.materialItem.id  //视频id
                    obj.image_id = creative.coverImage.id    // 视频封面图片id(必需)
                  } 
                  noMode.push(obj)
                }
                item.creative.creatives = noMode
              }

              // 如果广告组是单个商品
              for (const campaigns of this.mapData.campaign) {
                if( campaigns.id === item.ad.campaign_id && campaigns.delivery_related_num === 'CAMPAIGN_DPA_SINGLE_DELIVERY' ){
                  if( !item.ad.productPlatform ) return alert(`${item.name}( ${item.account_id} ),第${item.key}条计划,请选择关联小说`),this.id_Loading =false
                  item.ad.product_platform_id = item.ad.productPlatform.product_platform_id
                  item.ad.product_id = item.ad.productPlatform.product_id
                  break;
                };
              }
              delete item.ad.productPlatform

              item.ad.name = `${ item.ad.name }|${ item.logoName }|`
              //删除定向包[]
              delete item.ad.package
              // 落地页链接拼接id
              item.ad.cpa_bid = item.ad.cpa_bid.toString() // 出价转化为字符串（ 精度问题 ） JSON.stringify()

              delete item.key
              subimt.items.push( item )
            }
          }
          subimt.items[0].view = this.$store.state.batchCreated.echoView

          batchCreate(subimt).then((res)=>{
            if( res.code === 'SUCCESS' ){
              this.$message.success(res.message)
              window.open('#/batch/task', '_blank');
            }
            this.id_Loading =false
          })

        } else {
          return false;
        }
      });
    }
  },
}
</script>

<style lang="less" scoped>
  .selectBtn{
    display: flex;
  }
  .table-btn{
    margin-bottom:10px;
    span{
      margin-right:20px;
    }
  }
  // 分批
  .chunk-flex{
    padding-left: 100px;
    display: flex;
  }
  .ant-row , .ant-form-item{
    margin: 0 10px;
  }

  .check-table{
    width: 100%;
    max-height: 500px;
    padding: 0 10px;
    overflow: auto;
  }
  // 滚动条（所有滚动条）
  .check-table::-webkit-scrollbar{
    background: white;
    width: 10px;
    height: 10px;
  }
  .check-table::-webkit-scrollbar-thumb{
    background: #c2bcbc;
    opacity: 0.1;
    border-radius: 20px;
  }
  .check-table::-webkit-scrollbar-button{
    display: none;
  }
</style>